package flex.cc.complain.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.common.utils.OrderNoGenerateUtil;
import flex.cc.complain.dao.ComplainDao;
import flex.cc.complain.entity.ComplainEntity;
import flex.cc.complain.entity.ComplainTrackEntity;
import flex.cc.complain.service.ComplainService;
import flex.cc.complain.service.ComplainTrackService;
import flex.cc.complain.vo.ComplainVo;
import flex.cc.core.utils.RequestUtil;
import flex.cc.order.manage.dto.order.OrderCustomerEntity;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.dto.vo.OrderMainVo;
import flex.cc.order.manage.service.OrderCustomerService;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.util.ExportUtil;
import lombok.extern.slf4j.Slf4j;

@Service("complainService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class ComplainServiceImpl extends ServiceImpl<ComplainDao, ComplainEntity> implements ComplainService {
	@Autowired
	private OrderMainService orderMainService;
	@Autowired
	private OrderCustomerService orderCustomerService;
	@Autowired
	private ComplainTrackService complainTrackService;
	@Autowired
	private ComplainDao complainDao;
	@Autowired
    private OrderNoGenerateUtil orderNoGenerateUtil;
	@Autowired
	private DictCodeService dictCodeService;
	@Override
	public IPage<ComplainVo> queryComplainList(Map map){
		log.info("<<<<<<<<<投诉查询>>>>>>>");
		List<DictCodeEntity> dictCodelist = dictCodeService.list(new QueryWrapper<DictCodeEntity>().eq("type_code", "orderStatus"));
		IPage<ComplainEntity> page = new Page<>(Integer.parseInt(map.get("pageNum").toString()),Integer.parseInt(map.get("pageSize").toString()));
		
		IPage<ComplainVo> page2 = complainDao.queryComplainList(page,map);
		List<ComplainVo> list = page2.getRecords();
		for(ComplainVo entity:list) {
			OrderMainVo vo = new OrderMainVo();
			vo.setOrderNo(entity.getFworder());
			OrderMainVo queryOrderByNo = orderMainService.queryOrderByNo(vo);
			if(PublicUtil.isNotEmpty(queryOrderByNo)) {
				entity.setSourcename(queryOrderByNo.getSourceName());
				entity.setServername(queryOrderByNo.getServerName());
				if(PublicUtil.isNotEmpty(dictCodelist)) {
					for(int i=0;i<dictCodelist.size();i++) {
						DictCodeEntity dictCodeEntity = dictCodelist.get(i);
						if(dictCodeEntity.getCode().equals(queryOrderByNo.getStatus())) {
							entity.setFworderstate(dictCodeEntity.getValue());
							break;
						}
					}
				}
			}
			if("0".equals(entity.getComplainchannel())) {
				entity.setComplainchannel("渠道来电");
			}else if("1".equals(entity.getComplainchannel())) {
				entity.setComplainchannel("渠道沟通群");
			}else if("2".equals(entity.getComplainchannel())) {
				entity.setComplainchannel("客户来电");
			}
			if("0".equals(entity.getState())) {
				entity.setState("进展中");
			}else if("1".equals(entity.getState())) {
				entity.setState("已结案");
			}
		}
		return page2;
	}

	@Override
	public void saveComplainInfo(ComplainVo vo) {
		LoginAuthDto loginUser = RequestUtil.getLoginUser();
		ComplainEntity entity = new ComplainEntity();
		try {
			String dbFlag = "create";
			if(PublicUtil.isEmpty(vo.getId())) {//新增
				BeanUtils.copyProperties(entity, vo);
				entity.setInserttime(new Date());
				entity.setVersion(0);
				entity.setState("0");//进展中
				String tsnumber = getTsnumber(vo.getFworder());
				entity.setTsnumber(tsnumber);
				entity.setComcode(loginUser.getComCode());
				entity.setComplaintime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(vo.getComplaintimes()));
				OrderMainVo queryVo = new OrderMainVo();
				queryVo.setOrderNo(vo.getFworder());
				String username = orderCustomerService.queryCustomerByNo(queryVo);
				entity.setComplainant(username);//联系人
			}else {//编辑
				dbFlag = "update";
				BeanUtils.copyProperties(entity, vo);
//			    ComplainEntity one = this.getOne(new QueryWrapper<ComplainEntity>().eq("id", Long.valueOf(vo.getId())));
			    entity.setUpdateTime(new Date());
//			    entity.setVersion(one.getVersion()+1);
//			    entity.setDealcount(String.valueOf(Integer.parseInt(one.getDealcount())+1));
			}
			this.saveTrackInfo(entity);
			if("create".equals(dbFlag)){
				this.insert(entity);
			}else{
				this.update(entity);
			}
//			this.saveOrUpdate(entity);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}            
		
	}

	public int insert(ComplainEntity entity){
		return complainDao.insert(entity);
	}
	
	public int update(ComplainEntity entity){
		return complainDao.update(entity);
	}
	
	@Override
	public List<OrderMainEntity> querySearchAsync(String pam,String mobilephone) {
		List<OrderMainEntity> dataList = new ArrayList<OrderMainEntity>();
		OrderMainVo vo = new OrderMainVo();
		vo.setOrderNo(pam);
		vo.setMobile(mobilephone);
		List<Map<String,String>> list = orderMainService.querySearchAsync(vo);
		for(int i=0;i<list.size();i++) {
			OrderMainEntity entity = new OrderMainEntity();
			Map<String, String> map = list.get(i);
			entity.setOrderNo(map.get("orderNo"));
			dataList.add(entity);
		}
		return dataList;
	}

	@Override
	public List<OrderCustomerEntity> querySearchAsyncMobilephone(String pam) {
		List<OrderCustomerEntity> dataList = new ArrayList<OrderCustomerEntity>();
		OrderMainVo vo = new OrderMainVo();
		vo.setMobile(pam);
		List<Map<String,String>> list = orderCustomerService.querySearchAsyncMobile(vo);
		for(int i=0;i<list.size();i++) {
			OrderCustomerEntity entity = new OrderCustomerEntity();
			Map<String, String> map = list.get(i);
			entity.setMobile(map.get("mobile"));
			dataList.add(entity);
		}
		return dataList;
	}
	
	/**
	 * 新增操作轨迹
	 * */
	private void saveTrackInfo(ComplainEntity entity) {
		LoginAuthDto loginUser = RequestUtil.getLoginUser();
		ComplainTrackEntity data = new ComplainTrackEntity();
		data.setComcode(loginUser.getComCode());
		data.setUsercode(loginUser.getUserCode());
		data.setUsername(loginUser.getUserName());
		data.setTsnumber(entity.getTsnumber());
		data.setMemoinfo(PublicUtil.isEmpty(entity.getDealresult())?entity.getComplaincontent():entity.getDealresult());
		data.setInserttime(new Date());
		if(PublicUtil.isEmpty(entity.getId())) {
			data.setStatus("0");
		}else if(PublicUtil.isNotEmpty(entity.getId()) && "0".equals(entity.getState())) {
			data.setStatus("1");
		}else if("1".equals(entity.getState())) {
			data.setStatus("2");
		}
		this.complainTrackService.save(data);
	}
    /**
             * 导出
             * 导出字段包括  投诉单号、服务单号、投诉来源、渠道来源、服务商、投诉单状态（进展中、已结案），
             * 服务单状态、投诉日期（年月日）、投诉时间、投诉登记时间、投诉记录、处理次数、
             * 结案时长（结案时间-投诉时间），
             * 投诉次数（同一服务单投诉次数累计） 
     * */
	@Override
	public Map<String, Object> downZgInfo(Map map, LoginAuthDto loginAuthDto) {
		List<ComplainVo> list = complainDao.queryComplainAll(map);
		List<DictCodeEntity> dictCodelist = dictCodeService.list(new QueryWrapper<DictCodeEntity>().eq("type_code", "orderStatus"));
		if(!PublicUtil.isEmpty(list)) {
			Map<String, Object> returnMap = new ConcurrentHashMap<String, Object>();
			returnMap.put("templateName", "投诉清单");
			SXSSFWorkbook wb = ExportUtil.createWorkbook(10, true);//创建工作簿对象
            Sheet sheet = wb.createSheet("投诉清单");
            sheet.setColumnWidth(0, 26 * 256);
            sheet.setColumnWidth(1, 26 * 256);
            sheet.setColumnWidth(2, 18 * 256);
            sheet.setColumnWidth(3, 18 * 256);
            sheet.setColumnWidth(4, 18 * 256);
            sheet.setColumnWidth(5, 18 * 256);
            sheet.setColumnWidth(6, 18 * 256);
            sheet.setColumnWidth(7, 18 * 256);
            sheet.setColumnWidth(8, 18 * 256);
            sheet.setColumnWidth(9, 18 * 256);
            sheet.setColumnWidth(10, 18 * 256);
            sheet.setColumnWidth(11, 18 * 256);
            sheet.setColumnWidth(12, 18 * 256);
            sheet.createFreezePane(0, 1);
            Row row   = null;
            Cell cell = null;
            String[] title = {"投诉单号","服务单号","投诉来源","渠道来源","服务商","投诉单状态","服务单状态","投诉日期","投诉时间","投诉登记时间","投诉记录","处理次数","结案时长","投诉次数"};
            row = sheet.createRow(0);
            for(int i=0;i<title.length;i++) {
            	String string = title[i];
            	cell = row.createCell(i);
            	cell.setCellValue(string);
            }
            Map<String, String> dealCountMap = queryComplainCountByFworder();
            Map<String, String> trackMap = complainTrackService.queryComplainTrackByTsnumber();
            Map<String, String> dealTimesMap = queryComplainDealTimesByTsnumber();
            for(int i=0;i<list.size();i++) {
            	ComplainVo entity = list.get(i);
            	OrderMainVo vo = new OrderMainVo();
				vo.setOrderNo(entity.getFworder());
				OrderMainVo queryOrderByNo = orderMainService.queryOrderByNo(vo);
				String sourceName = null;
				String serverName = null;
				String status = null;
				if(PublicUtil.isNotEmpty(queryOrderByNo)) {
					sourceName = queryOrderByNo.getSourceName();
					serverName = queryOrderByNo.getServerName();
					status = queryOrderByNo.getStatus();
					if(PublicUtil.isNotEmpty(dictCodelist)) {
						for(int p=0;p<dictCodelist.size();p++) {
							DictCodeEntity dictCodeEntity = dictCodelist.get(p);
							if(dictCodeEntity.getCode().equals(queryOrderByNo.getStatus())) {
								status =dictCodeEntity.getValue();
								break;
							}
						}
					}
				}
				row = sheet.createRow(i+1);
				cell = row.createCell(0);
				cell.setCellValue(entity.getTsnumber());
				cell = row.createCell(1);
				cell.setCellValue(entity.getFworder());
				cell = row.createCell(2);
				if("0".equals(entity.getComplainchannel())) {
					cell.setCellValue("渠道来电");
				}else if("1".equals(entity.getComplainchannel())) {
					cell.setCellValue("渠道沟通群");
				}else if("2".equals(entity.getComplainchannel())) {
					cell.setCellValue("客户来电");
				}
				cell = row.createCell(3);
				cell.setCellValue(PublicUtil.isEmpty(sourceName)?"":sourceName);
				cell = row.createCell(4);
				cell.setCellValue(PublicUtil.isEmpty(serverName)?"":serverName);
				cell = row.createCell(5);
				if("0".equals(entity.getState())) {
					cell.setCellValue("进展中");
				}else if("1".equals(entity.getState())) {
					cell.setCellValue("已结案");
				}
				cell = row.createCell(6);
				cell.setCellValue(PublicUtil.isEmpty(status)?"":status);
				cell = row.createCell(7);
				cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getComplaintime()).substring(0, 10));
				cell = row.createCell(8);
				cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getComplaintime()));
				cell = row.createCell(9);
				cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.getInserttime()));
				cell = row.createCell(10);
				cell.setCellValue(PublicUtil.isEmpty(trackMap.get(entity.getTsnumber()))?"":trackMap.get(entity.getTsnumber()));
				cell = row.createCell(11);
				cell.setCellValue(entity.getDealcount());
				cell = row.createCell(12);
				cell.setCellValue(PublicUtil.isEmpty(dealTimesMap.get(entity.getTsnumber()))?"":dealTimesMap.get(entity.getTsnumber())+"小时");
				cell = row.createCell(13);
				cell.setCellValue(PublicUtil.isEmpty(dealCountMap.get(entity.getFworder()))?"":dealCountMap.get(entity.getFworder()));
				
            }
            //首行
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] fileByte = null;
            try {
				wb.write(bos);
				fileByte  = bos.toByteArray();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
            returnMap.put("fileByte", fileByte);
            return returnMap;
		}
		return null;
	}

	@Override
	public Map<String, String> queryComplainCountByFworder() {
		List<ComplainVo> list = this.complainDao.queryComplainCountByFworder();
		Map<String,String> returnMap = new ConcurrentHashMap<String, String>();
		if(PublicUtil.isNotEmpty(list)) {
			for(int i=0;i<list.size();i++) {
				ComplainVo vo = list.get(i);
				returnMap.put(vo.getFworder(), vo.getDealcount());
			}
		}
		return returnMap;
	}

	@Override
	public Map<String, String> queryComplainDealTimesByTsnumber() {
		List<ComplainVo> list = this.complainDao.queryComplainDealTimesByTsnumber();
		Map<String,String> returnMap = new ConcurrentHashMap<String, String>();
		if(PublicUtil.isNotEmpty(list)) {
			for(int i=0;i<list.size();i++) {
				ComplainVo vo = list.get(i);
				returnMap.put(vo.getTsnumber(), vo.getDealtimes());
			}
		}
		return returnMap;
	}

	@Override
	public String checkOrderStatusByFwOrder(Map map) {
		String flag ="0";
		List<ComplainEntity> list = this.list(new QueryWrapper<ComplainEntity>().eq("fworder", map.get("fworder")).eq("state", "0"));
		if(PublicUtil.isNotEmpty(list)) {
			flag ="1";
		}
		return flag;
	}
    /**
     * ZXTS年月日-01救援商编码-01顺序编码
     * */
	@Override
	public String getTsnumber(String fworder) {
		OrderMainVo vo = new OrderMainVo();
		vo.setOrderNo(fworder);
		OrderMainVo orderMainVo = this.orderMainService.queryOrderByNo(vo);
		String serverId = orderMainVo.getServerId();
		String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
		
		Map<String, String> map = this.complainDao.queryQuence("seq_ts");
		String years = null;
		String orderNo = null;
		if(PublicUtil.isNotEmpty(map)) {
			years = map.get("years");
		}
		if(!PublicUtil.getCurrentDateStr().equals(years)) {
			//1、重置序列成1  2、更新序列表时间years
			orderNoGenerateUtil.updateSequenceTimeByName("seq_ts");
			orderNo = orderNoGenerateUtil.resetSequenceByName("seq_ts");
		}else {
			orderNo = orderNoGenerateUtil.generateBusinessNo("seq_ts"); // TODO 默认渠道名称是电话中心-01
		}
		String tsnumber = "ZXTS"+currentDate+"01"+orderNo;
		return tsnumber;
	}

	@Override
	public String checkFwOrderStatus(Map map) {
		OrderMainVo vo = new OrderMainVo();
		vo.setOrderNo(map.get("fworder").toString());
		String status = this.orderMainService.checkFwOrderStatus(vo);
		return status;
	}

}
